package cn.tang.tframe.sdm.utils;

import cn.tang.tframe.common.utils.lang.StringUtils;
import cn.tang.tframe.sdm.web.shiro.realm.IShiroUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.subject.WebSubject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

public class ShiroUtils {
	private static Logger logger = LoggerFactory.getLogger(ShiroUtils.class);

	public static <T extends IShiroUser> T getCurrentUser() {
		Subject subject = SecurityUtils.getSubject();
		if(null != subject){
			return (T) subject.getPrincipal();
		}
		return null;
	}
	public static <PK extends Serializable> PK getCurrentUserId() {
		IShiroUser currentUser = getCurrentUser();
		return null != currentUser? (PK) currentUser.getUid() :null;
	}
	public static void logoutSafe() {
		Subject subject = SecurityUtils.getSubject();
		if(null != subject){
			try {
				subject.logout();
			} catch (Exception e) {
				logger.info("safe logout fail: {}",e.getMessage());
			}
		}
	}

	public static long getSessionTimeOut() {
		return SecurityUtils.getSubject().getSession(false).getTimeout();
	}

	public static Serializable getCurrentSessionId() {
		return SecurityUtils.getSubject().getSession(false).getId();
	}


	public static String getHeaderOrParameter(String key) {
		ServletRequest request = ((WebSubject) SecurityUtils.getSubject()).getServletRequest();
		String header = "";
		if (request instanceof HttpServletRequest) {
			header = ((HttpServletRequest) request).getHeader(key);
			if(StringUtils.isNotBlank(header)){
				return header;
			}
			header = (request).getParameter(key);
		}
		return header;
	}
	public static String getParameterOrHeader(String key) {
		ServletRequest request = ((WebSubject) SecurityUtils.getSubject()).getServletRequest();
		String header = (request).getParameter(key);
		if(StringUtils.isNotBlank(header)){
			return header;
		}
		if (request instanceof HttpServletRequest) {
			header = ((HttpServletRequest) request).getHeader(key);
			if (header != null && header.length() > 0) {
				return header;
			}
			header = (request).getParameter(key);
		}
		return header;
	}

	public static String getHeader(String headerName) {
		ServletRequest request = ((WebSubject) SecurityUtils.getSubject()).getServletRequest();
		String header = "";
		if (request instanceof HttpServletRequest) {
			header = ((HttpServletRequest) request).getHeader(headerName);
			if (header != null && header.length() > 0) {
				return header;
			}
		}
		return header;
	}
	public static String getIp() {
		ServletRequest request = ((WebSubject) SecurityUtils.getSubject()).getServletRequest();
		if (request instanceof HttpServletRequest) {
			return IpUtils.getRealIp((HttpServletRequest) request) ;
		}
		return "";
	}

}
